/**
 * 国际化核心库
 * xxpay Agent System Internationalization
 */
(function(window) {
    'use strict';

    var I18n = {
        // 当前语言
        locale: 'zh_CN',
        
        // 消息映射
        messages: {},
        
        // 支持的语言
        supportedLocales: ['zh_CN', 'en_US'],
        
        // 默认语言
        defaultLocale: 'zh_CN',
        
        // 存储键名
        storageKey: 'xxpay_agent_locale',
        
        /**
         * 初始化国际化
         */
        init: function(locale) {
            this.locale = locale || this.getStoredLocale() || this.getBrowserLocale() || this.defaultLocale;
            this.loadMessages();
            this.updatePageElements();
        },
        
        /**
         * 获取翻译文本
         */
        t: function(key, params) {
            var message = this.messages[key] || key;
            
            // 参数替换
            if (params) {
                if (typeof params === 'object') {
                    for (var param in params) {
                        var regex = new RegExp('\\{' + param + '\\}', 'g');
                        message = message.replace(regex, params[param]);
                    }
                } else if (Array.isArray(params)) {
                    for (var i = 0; i < params.length; i++) {
                        var regex = new RegExp('\\{' + i + '\\}', 'g');
                        message = message.replace(regex, params[i]);
                    }
                }
            }
            
            return message;
        },
        
        /**
         * 设置语言
         */
        setLocale: function(locale) {
            if (this.supportedLocales.indexOf(locale) === -1) {
                console.warn('Unsupported locale: ' + locale);
                return false;
            }
            
            this.locale = locale;
            this.storeLocale(locale);
            this.loadMessages();
            this.updatePageElements();
            
            // 触发语言切换事件
            this.trigger('localeChanged', {
                locale: locale,
                messages: this.messages
            });
            
            return true;
        },
        
        /**
         * 获取当前语言
         */
        getLocale: function() {
            return this.locale;
        },
        
        /**
         * 获取存储的语言偏好
         */
        getStoredLocale: function() {
            try {
                return localStorage.getItem(this.storageKey);
            } catch (e) {
                return null;
            }
        },
        
        /**
         * 存储语言偏好
         */
        storeLocale: function(locale) {
            try {
                localStorage.setItem(this.storageKey, locale);
            } catch (e) {
                console.warn('Cannot store locale preference');
            }
        },
        
        /**
         * 获取浏览器语言
         */
        getBrowserLocale: function() {
            var lang = navigator.language || navigator.userLanguage;
            if (lang) {
                // 转换为标准格式
                if (lang.indexOf('zh') === 0) {
                    return 'zh_CN';
                } else if (lang.indexOf('en') === 0) {
                    return 'en_US';
                }
            }
            return null;
        },
        
        /**
         * 加载语言包
         */
        loadMessages: function() {
            // 根据当前语言加载对应的消息
            if (this.locale === 'en_US' && window.I18N_MESSAGES_ENUS) {
                this.messages = window.I18N_MESSAGES_ENUS;
            } else if (this.locale === 'zh_CN' && window.I18N_MESSAGES_ZHCN) {
                this.messages = window.I18N_MESSAGES_ZHCN;
            } else {
                // 动态加载语言包
                this.loadLanguageScript();
            }
        },
        
        /**
         * 动态加载语言包脚本
         */
        loadLanguageScript: function() {
            var script = document.createElement('script');
            script.src = '/static/i18n/' + this.locale + '.js';
            script.onload = function() {
                this.loadMessages();
                this.updatePageElements();
            }.bind(this);
            document.head.appendChild(script);
        },
        
        /**
         * 更新页面元素
         */
        updatePageElements: function() {
            var elements = document.querySelectorAll('[data-i18n]');
            for (var i = 0; i < elements.length; i++) {
                var element = elements[i];
                var key = element.getAttribute('data-i18n');
                var text = this.t(key);
                
                // 根据元素类型设置文本
                if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                    if (element.type === 'button' || element.type === 'submit') {
                        element.value = text;
                    } else {
                        element.placeholder = text;
                    }
                } else {
                    element.textContent = text;
                }
            }
        },
        
        /**
         * 事件系统
         */
        events: {},
        
        /**
         * 绑定事件
         */
        on: function(event, callback) {
            if (!this.events[event]) {
                this.events[event] = [];
            }
            this.events[event].push(callback);
        },
        
        /**
         * 触发事件
         */
        trigger: function(event, data) {
            if (this.events[event]) {
                for (var i = 0; i < this.events[event].length; i++) {
                    this.events[event][i](data);
                }
            }
        },
        
        /**
         * 格式化数字
         */
        formatNumber: function(number, decimals) {
            decimals = decimals || 0;
            return Number(number).toLocaleString(this.locale.replace('_', '-'), {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals
            });
        },
        
        /**
         * 格式化货币
         */
        formatCurrency: function(amount, currency) {
            currency = currency || 'CNY';
            return Number(amount).toLocaleString(this.locale.replace('_', '-'), {
                style: 'currency',
                currency: currency
            });
        },
        
        /**
         * 格式化日期
         */
        formatDate: function(date, format) {
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            
            format = format || 'YYYY-MM-DD HH:mm:ss';
            
            var year = date.getFullYear();
            var month = ('0' + (date.getMonth() + 1)).slice(-2);
            var day = ('0' + date.getDate()).slice(-2);
            var hour = ('0' + date.getHours()).slice(-2);
            var minute = ('0' + date.getMinutes()).slice(-2);
            var second = ('0' + date.getSeconds()).slice(-2);
            
            return format
                .replace('YYYY', year)
                .replace('MM', month)
                .replace('DD', day)
                .replace('HH', hour)
                .replace('mm', minute)
                .replace('ss', second);
        }
    };
    
    // 暴露到全局
    window.I18n = I18n;
    
    // 自动初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            I18n.init();
        });
    } else {
        I18n.init();
    }
    
})(window);
